package com.wwinsoft.framework.dao.security;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.stereotype.Component;

import com.wwinsoft.framework.entity.security.MemberShip;
import com.wwinsoft.framework.entity.security.MemberShipPK;
import com.wwinsoft.modules.orm.hibernate.HibernateDao;

/**
 * 会员关系的泛型DAO.
 *
 */
@Component
public class MemberShipDao extends HibernateDao<MemberShip, MemberShipPK> {

    private static final String QUERY_MEMBERSHIP_BY_USERID = "select m.USER_ID_, m.GROUP_ID_ from act_id_membership m where m.USER_ID_=:userId";
    private static final String QUERY_MEMBERSHIP_BY_GROUPID = "select m.USER_ID_, m.GROUP_ID_ from act_id_membership m where m.GROUP_ID_=:groupId";
    
    private static final String DELETE_BY_GROUPID = "delete from act_id_membership where group_id_ = :groupId";
    private static final String UPDATE_BY_GROUPID = "update act_id_membership m set m.group_id_ = :newGroupId where m.group_id_ = :oldGroupId";

    /**
     * 根据用户ID获取会员关系列表
     * 
     * @param userId
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Object[]> getMemberShipListByUserId(String userId) {
        Map paraMap = new HashMap();
        paraMap.put("userId", userId);
        Query query = createSQLQuery(QUERY_MEMBERSHIP_BY_USERID, paraMap);
        return query.list();
    }
    
    /**
     * 根据部门ID获取会员关系列表
     * 
     * @param groupId
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Object[]> getMemberShipListByGroupId(String groupId) {
        Map paraMap = new HashMap();
        paraMap.put("groupId", groupId);
        Query query = createSQLQuery(QUERY_MEMBERSHIP_BY_GROUPID, paraMap);
        return query.list();
    }
    
    /**
     * 查询属于该组织部门的用户并删除用户部门关系
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public int deleteByGroupId(String groupId) {
        Map paraMap = new HashMap();
        paraMap.put("groupId", groupId);
        Query sqlQuery = this.createSQLQuery(DELETE_BY_GROUPID, paraMap);
        return sqlQuery.executeUpdate();
    }
    
    /**
     * 查询属于该组织部门的用户并更改部门ID
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public int updateGroupId(String oldGroupId, String newGroupId) {
        Map paraMap = new HashMap();
        paraMap.put("oldGroupId", oldGroupId);
        paraMap.put("newGroupId", newGroupId);
        Query sqlQuery = this.createSQLQuery(UPDATE_BY_GROUPID, paraMap);
        return sqlQuery.executeUpdate();
    }
}
